package org.example.chatroom.controller;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LIUYANJIAO
 * Date: 2025-06-21
 * Time: 17:06
 */

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.lang.Console;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.io.OutputStream;
@Slf4j
@RestController
@RequestMapping("user")
public class CodeController {

    @RequestMapping("getcode")
    public void getcode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 每次请求都创建新的验证码实例
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        HttpSession session = request.getSession();
        // 将验证码答案存到 session 中，用于后续验证
        session.setAttribute("captchaCode", lineCaptcha.getCode());

        OutputStream outputStream = response.getOutputStream();
        // 图形验证码写出到流
        lineCaptcha.write(outputStream);
        // 输出 code
        Console.log(lineCaptcha.getCode());
        outputStream.flush();
        outputStream.close();
    }

    @RequestMapping("checkcode")
    public boolean checkcode(HttpServletRequest request, String code) {
        log.info("code : "+code);
        HttpSession session = request.getSession();
        String correctCode = (String) session.getAttribute("captchaCode");
        if (correctCode != null) {
            log.info("correctCode："+correctCode);
            // 验证后移除验证码
            session.removeAttribute("captchaCode");
            return correctCode.equals(code);
        }
        return false;
    }
}